package me.zklh.transaction.north.local.impl;


import me.zklh.transaction.domain.entity.Account;
import me.zklh.transaction.domain.types.ExchangeRate;
import me.zklh.transaction.domain.types.Money;
import me.zklh.transaction.domain.service.AccountTransferService;
import me.zklh.transaction.north.local.TransferService;
import me.zklh.transaction.north.message.Result;
import me.zklh.transaction.domain.types.AuditEvent;
import me.zklh.transaction.south.port.client.ExchangeRateService;
import me.zklh.transaction.south.port.publisher.AuditPublisher;
import me.zklh.transaction.south.port.repository.AccountRepository;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Currency;

public class TransferServiceImpl implements TransferService {
    @Resource
    private AccountRepository accountRepository;

    @Resource
    private AuditPublisher auditPublisher;

    @Resource
    private ExchangeRateService exchangeRateService;

    @Resource
    private AccountTransferService accountTransferService;


    @Override
    public Result<Boolean> transfer(Long sourceUserId, String targetAccountNumber, BigDecimal targetAmount, String targetCurrency) {
        // 参数校验
        Money targetMoney = new Money(targetAmount, Currency.getInstance(targetCurrency));

        // 读数据
        Account sourceAccount = accountRepository.find(sourceUserId);
        Account targetAccount = accountRepository.find(targetAccountNumber);
        // 从外部服务中获取汇率
        ExchangeRate exchangeRate = exchangeRateService.getExchangeRate(sourceAccount.getCurrency(), targetMoney.getCurrency());

        // 业务逻辑
        accountTransferService.transfer(sourceAccount, targetAccount, targetMoney, exchangeRate);

        // 保存数据
        accountRepository.save(sourceAccount);
        accountRepository.save(targetAccount);

        // 发送审计消息
        AuditEvent event = new AuditEvent(sourceAccount, targetAccount, targetMoney);
        auditPublisher.send(event);

        return Result.success(true);
    }
}
